<?php

class FuelController extends AppController {

    public $uses = array('Fueler', 'FuelRequest','FuelRequestAttachment');
    public $components = array('Pdf','Upload');
    public $paginate = array(
        'FuelRequest' => array(
            'order' => array('id' => 'desc'),
            'limit' => 30
        )
    );
    
    function beforeFilter() {
        if ($this->Session->check('user') == false) {
            $this->redirect('/admin/users/login/');
        }
    }

    public function admin_index() {
        
    }

    public function admin_list() {
        if ($this->RequestHandler->isAjax()) {
            $this->autoLayout = false;

            $offset = isset($_GET['offset']) ? $_GET['offset'] : 0;
            $limit = 20;

            $this->set('pg_offset', $offset + 1);
            $this->set('pg_size', $limit);

            // if we are searching for a permit
            if (isset($_GET['term']) && $_GET['filter'] != "") {

                $request_search_term = "";

                /*if ($_GET['filter'] == "sb") {
                    $request_search_term = "FuelRequest.ref_no";
                } elseif ($_GET['filter'] == "pt") {
                    $request_search_term = "FuelRequest.aircraft_flight_no";
                } else if ($_GET['filter'] == "lc") {
                    $request_search_term = "FuelRequest.arr_dest";
                } else if ($_GET['filter'] == "cn") {
                    $request_search_term = "FuelRequest.company_name";
                } else if ($_GET['filter'] == "st") {
                    $request_search_term = "FuelRequest.status";
                } else if( $_GET['filter'] == "so" ) {
                    $request_search_term = "FuelRequest.confirmation_code";
                }*/
                
                $request_search_term = $_GET['filter'];


                //$requests = $this->FuelRequest->getRequestsByKey($request_search_term, $_GET['term']);
                //$count = ceil((count($requests) + 1) / $limit);
                $requests = $this->paginate('FuelRequest', array(
                    $request_search_term . " LIKE" => "%" . $_GET['term'] . "%"
                ));

                $this->set('requests', $requests);
                //$this->set('pages', $count);
                $this->set('status', 'open');
                $this->set('term', $_GET['term']);
            } else if (isset($_GET['status'])) {
                $requests = $this->paginate('FuelRequest', array(
                    'status' => $_GET['status']
                        ));

                $this->set('requests', $requests);
                $this->set('status', $_GET['status']);

                //$this->set('requests', $this->FuelRequest->getOpenRequests($offset, $limit));
                //$this->set('pages', ceil($this->FuelRequest->getTotalOpen() / $limit));
            } else {
                $this->set('requests', $this->FuelRequest->getClosedRequests($offset, $limit));
                $this->set('pages', ceil($this->FuelRequest->getTotalClosed() / $limit));
                $this->set('status', 'closed');
            }
        }
    }

    public function admin_requestForm($id = NULL) {

        if ($this->RequestHandler->isAjax() && isset($_POST['data'])) {
            $this->autoRender = false;

            $user = $this->Session->read('user');

            if (isset($_POST['data']['FuelRequest']['id']) && $_POST['data']['FuelRequest']['id'] == "") {
                $this->FuelRequest->create();
                $this->FuelRequest->set($_POST['data']['FuelRequest']);
                $this->FuelRequest->set(array(
                    'created_dt' => date('Y-m-d H:i:s'),
                    'created_by' => $user['User']['id'],
                    'status' => 'open'
                ));
                $this->FuelRequest->save();

                $this->FuelRequest->set('ref_no', 'SBF' . $this->FuelRequest->id . "-" . date('y'));
                $this->FuelRequest->save();
            } else {
                $this->FuelRequest->id = $_POST['data']['FuelRequest']['id'];
                $this->FuelRequest->set($_POST['data']['FuelRequest']);
                $this->FuelRequest->set(array(
                    'modified_dt' => date('Y-m-d H:i:s'),
                    'modified_by' => $user['User']['id']
                ));
                $this->FuelRequest->save();
            }
        }

        $fuelers = $this->Fueler->find('list');
        $this->set('fuelers', $fuelers);
        
        $info = $this->Fueler->query("SHOW TABLE STATUS LIKE 'fuel_requests'");
        $next_ref_no = "SBF" . $info[0]['TABLES']['Auto_increment'] . "-" . date('y');
        $this->set('next_ref_no', $next_ref_no);

        if ($id != NULL) {
            $this->set('fuelRequest', $this->FuelRequest->findById($id));
        }
    }

    public function admin_delete_request($request_id) {
        $this->autoRender = false;

        $user = $this->Session->read('user');
        $this->FuelRequest->id = $request_id;
        $this->FuelRequest->save(array(
            'status' => 'deleted',
            'modified_by' => $user['User']['id']
        ));
    }

    public function admin_request_summary($id) {
        $this->set('request', $this->FuelRequest->findById($id));
    }

    public function admin_changeStatus() {

        if( isset($_POST['data']) ) {
            $this->autoRender = false;
            
            $user = $this->Session->read('user');
            $data = $_POST['data'];
            $data['FuelRequestStatus'][0] = array(
                'status' => $data['FuelRequest']['status'],
                'change_dt' => date('Y-m-d H:i:s'),
                'changed_by' => $user['User']['id'],
                'comments' => $_POST['comments']
            );
            
            $this->FuelRequest->saveAll($data);
            
            return;
        }
        
        $request = $this->FuelRequest->find('first', array(
            'conditions' => array('FuelRequest.id' => $_POST['fuel_request_id']),
            'recursive' => -1)
        );

        $this->set('request', $request);
        $this->set('status', $_POST['status']);
    }

    /**
     * Displays the UI for previewing the request confirmation form
     * 
     */
    public function admin_requestConfirmation() {

        $request = $this->FuelRequest->find('first', array(
            'conditions' => array('FuelRequest.id' => $_POST['fuel_request_id'])
                ));

        $this->set('request', $request);
    }

    /**
     * Displays the UI for previewing the request confirmation form and triggering
     * a print action
     * 
     */
    public function admin_printRequestConfirmation($request_id, $options = '') {
        if ($options == 'download') {

            $user = $this->Session->read('user');
            $request = ClassRegistry::init('FuelRequest')->find('first', array('conditions' => array('id' => $request_id), 'recursive' => -1));

            $this->Pdf->download("fuel_request_confirmation_form_{$request['FuelRequest']['ref_no']}.pdf", '/elements/fuel/request_confirmation_content', array('request' => $request, 'show_footer' => true, 'staff' => $user));

            return;
        }

        $this->layout = "print_layout";

        $request = $this->FuelRequest->find('first', array(
            'conditions' => array('FuelRequest.id' => $request_id)
                ));

        $this->set('request', $request);
    }

    public function admin_sendRequestConfirmation($request_id) {
        $request = $this->FuelRequest->find('first', array(
            'conditions' => array('FuelRequest.id' => $request_id)
                ));

        $this->set('request', $request);
    }

    public function admin_viewRequest($request_id) {
        $request = $this->FuelRequest->find('first', array(
            'conditions' => array('FuelRequest.id' => $request_id)
                ));

        $this->set('request', $request);
    }

    public function admin_printRequest($request_id, $options = false) {

        if ($options == 'download') {

            $user = $this->Session->read('user');
            $request = ClassRegistry::init('FuelRequest')->find('first', array('conditions' => array('id' => $request_id), 'recursive' => -1));

            $this->Pdf->download("fuel_request_form_{$request['FuelRequest']['ref_no']}.pdf", '/elements/fuel/request_content', array('request' => $request, 'show_footer' => true, 'staff' => $user));

            return;
        }

        $this->layout = "print_layout";

        $request = $this->FuelRequest->find('first', array(
            'conditions' => array('FuelRequest.id' => $request_id)
                ));

        $this->set('request', $request);
    }

    public function admin_sendRequest($request_id) {
        $request = $this->FuelRequest->find('first', array(
            'conditions' => array('FuelRequest.id' => $request_id)
                ));

        $this->set('request', $request);
    }

    public function admin_confirmationForm($request_id = NULL) {

        if (isset($_POST['data']['FuelRequest'])) {
            $this->autoRender = false;

            $user = $this->Session->read('user');
            $_POST['data']['FuelRequest']['confirmation_dt'] = date('Y-m-d H:i:s');
            $_POST['data']['FuelRequest']['confirmed_by'] = $user['User']['id'];
            $_POST['data']['FuelRequest']['status'] = "approved";

            $this->FuelRequest->save($_POST['data']['FuelRequest']);

            return;
        }

        $request = $this->FuelRequest->find('first', array(
            'conditions' => array('FuelRequest.id' => $request_id)
                ));

        $this->set('request', $request);
    }

    public function admin_addAttachment() {
        
        if (isset($_POST['data'])) {
            $this->autoRender = false;
            
            $user = $this->Session->read('user');

            if (isset($_FILES['attachments'])) {
                $attachments = $this->Upload->uploadFiles($_FILES['attachments']);
                $data = array();

                foreach ($attachments as $attachment) {
                    $att = array(
                        'fuel_request_id' => $_POST['data']['FuelRequestAttachment']['fuel_request_id'],
                        'mime_type' => $attachment['mime_type'],
                        'file_name' => $attachment['file_name'],
                        'attachment' => $attachment['data']
                    );
                    
                    if( isset($_POST['data']['FuelRequestAttachment']['id']) ) {
                        $att['id'] = $_POST['data']['FuelRequestAttachment']['id'];
                        $att['modified_by'] = $user['User']['id'];
                    }
                    
                    else {
                        $att['created_dt'] = date('Y-m-d H:i:s');
                        $att['created_by'] = $user['User']['id'];
                    }
                    
                    $data[] = $att;
                }

                $this->FuelRequestAttachment->saveAll($data);
            }
            
            return;
        }
        
        $fuel_request_id = $_POST['fuel_request_id'];
        
        $fuel_request_attachments = $this->FuelRequestAttachment->find('all', array(
            'fields' => array('id', 'file_name', 'created_dt'),
            'conditions' => array('FuelRequestAttachment.fuel_request_id' => $fuel_request_id),
            'recursive' => -1
        ));
        
        $this->set('fuel_request_id', $fuel_request_id);
        $this->set('fuel_request_attachments', $fuel_request_attachments);
    }
    
    public function admin_deleteAttachment($fuel_request_attachment_id) {
        $this->autoRender = false;
        
        $this->FuelRequestAttachment->id = $fuel_request_attachment_id;
        $this->FuelRequestAttachment->delete();
    }
    
    public function admin_viewAttachment($fuel_request_attachment_id) {
        $this->autoRender = false;
        
        $attachment = $this->FuelRequestAttachment->find('first', array(
            'conditions' => array('FuelRequestAttachment.id' => $fuel_request_attachment_id),
            'recursive' => -1
        ));
        
        header("Content-type: " . $attachment['FuelRequestAttachment']['mime_type']);
        header("Content-Disposition: inline; filename=\"" . $attachment['FuelRequestAttachment']['file_name'] . "\"");

        echo $attachment['FuelRequestAttachment']['attachment'];
    }
}

?>
